<?php


namespace Biz\service\advertisement\position;

use Biz\model\activity\BizProjectGroupModel;
use Biz\model\advertisement\MPosition;
use Biz\service\admin\tools\SimplePageTpl;
use Biz\service\advertisement\AdAdmin;
use Biz\service\advertisement\AdConfManagement;
use Biz\service\advertisement\AdPositionManagement;
use Biz\service\advertisement\position\dao\BizPositionManagementDao;
use Biz\service\advertisement\position\model\BizPositionManagementModel;
use Doraemon\model\Admin\BeerUsUser;
use Doraemon\pockets\constInterface\LinkConf;
use Doraemon\service\position\AdmOperationModule;
use Doraemon\service\position\ConstInterface;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\Msg2Admin;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Exception;
use Illuminate\Http\Request;

class BizPositionManagement extends BizPositionPageTpl
{

    const TPL_CONFIG_TPL_NAME = 'APP固定资源位';

    const STYLE_MAP = [
        '' => '[自定义]',
        'single_banner' => '单图',
        'single_float_banner' => '悬浮图',
        'carousel_banner' => '轮播图',
        'carousel_banner_with_pos' => '带位置的轮播图',
        'broadcast_with_pos' => '带位置的广播',
        'card_with_pos' => '带位置的卡片',
        'custom_banner' => '自定义 banner',
        'custom_card' => '自定义卡片',
    ];
    private ?BizPositionManagementDao $data = null;
    private array $versionOptions = [];
    private array $tabOptions = [];

    public function init(Request $request, $pid = 0): SimplePageTpl
    {
        $this->data = new BizPositionManagementModel();
        $conf = AdPositionManagement::getConf();
        $sort = array_column($conf, 'sort');
        array_multisort($sort, SORT_ASC, $conf);
        foreach ($conf as $v) {
            $version = $v['v'] ?? '';
            $tab = $v['tab'] ?? '';
            $tabs = is_string($tab) ? explode(',', $tab) : $tab;
            $this->versionOptions[$version] = $version;
            foreach ($tabs as $tab) {
                $this->tabOptions[$tab] = $tab;
            }
        }
        return parent::init($request, $pid);
    }

    public function getList(): array
    {
        return $this->data->list($this->getRequestCondition());
    }

    public function getTotal(): int
    {
        return 0;
    }

    public function condition(): array
    {
        $tab = $this->getRequest()->input('tab', []);
        $style = $this->getRequest()->input('style', []);
        $v = $this->getRequest()->input('v', []);
        $name = $this->getRequest()->input('name', '');
        $condition = [];

        if ($tab) $condition['tab'] = $tab;
        if ($style) $condition['style'] = $style;
        if ($v) $condition['v'] = $v;
        if ($name) $condition['name'] = $name;

        return $condition;
    }

    public function getGrid(Grid $grid)
    {
        $multipleSelectLen = 120;
        $grid->disablePagination();
        $grid->column('id')->width(80)->sort();
        $grid->column('_info', '信息')->display(function (){
            $display = [
                '资源位名称:' . $this->title,
                '标识:' . $this->en_name,
            ];
            if ($this->alias) $display[] = '别名:' . implode(" ", $this->alias);
            if ($this->v) $display[] = '版本信息:' . $this->v;
            $display[] = 'statSign:' . $this->sign;
            return implode('<br/>', $display);
        });
        $grid->column('style_type', '类型')->select(self::STYLE_MAP);
        $grid->column('tab', '位置标签')->label();
        $grid->column('rel', '占位')->using(MPosition::REL_MAP)->dot([
            MPosition::REL_CLOSE => 'warning',
            MPosition::REL_OPEN => 'success',
        ]);
        $grid->column('uri', '配置跳转链接')->link()->copyable();
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
            $actions->disableDelete();
        });

        $grid->filter(function (Grid\Filter $filter) {
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            $filter->column(1 / 2, function (Grid\Filter $filter) {
                $filter->equal('tab', '资源位位置')->multipleSelect($this->tabOptions);
                $filter->equal('style', '类型')->multipleSelect(self::STYLE_MAP);
            });

            $filter->column(1 / 2, function (Grid\Filter $filter) {
                $filter->equal('v', '支持app版本')->multipleSelect($this->versionOptions);
                $filter->equal('name', '标识');
            });
            $filter->expand();
        });
    }

    public function getForm(Form $form)
    {
        $form->confirm('确认配置正确?');
        $form->id('id')->help('*api 中使用');
        $states = [
            'on'  => ['value' => AdConfManagement::REL_OPEN, 'text' => '打开', 'color' => 'success'],
            'off' => ['value' => AdConfManagement::REL_CLOSE, 'text' => '关闭', 'color' => 'danger'],
        ];
        $form->switch('rel', '占位系统关联')->states($states)->help('*api 中使用');
        $form->text('options.rel_pos', '占位开放位置')->help('配置格式:1,3,5;使用,分隔');
        $form->radioCard('style_type', '资源位展示类型')->options(self::STYLE_MAP)->required()->help('*api 中使用')
        ->when('custom_card', function (Form $form) {
            $form->radio('options.card_banner', '是否支持 banner')->options(['不支持','支持']);
        });
        $form->radio('options.pic', '开启图片配置')->options(['否','是'])
            ->when(1, function (Form $form) {
                $form->text('options.img_area', '图片宽高限制')->help("格式: 宽,高; 750,170; 500,625;")->default('750,170');
                $form->text('options.img_size', '图片大小限制')->help("常用数值:102400 204800 409600 512000 819200")->default(204800);
                $form->number('options.pos', '图片数量限制')->default(5);
                $form->number('options.gap', '播放时间间隔')->default(3);
                $form->multipleSelect('options.banner_link', '支持链接类型')->options($this->linkOptions());
            });
        $form->radio('options.card', '开启卡片配置')->options(['否','是'])
            ->when(1, function (Form $form) {
                $form->text('options.card_pos', '开放位置')->default(20)->help('配置格式:1,3,5;使用,分隔;或者一个数字代表 1~n');;
                $form->multipleSelect('options.card_link', '支持链接类型')->options($this->linkOptions());
            });
        $form->multipleSelect('drop_version', '功能')->options(AdConfManagement::FIELD_MAP)->help('*api 中使用');
        $form->tags('en_name', '资源位标识')->required();
        $form->text('title', '资源位名称');
        $form->text('sign', '埋点标识');
        $form->tags('tab', '位置名称')->help("已经存在的位置:" . implode(" ", $this->tabOptions));
        $form->text('v', '支持app版本')->help("格式: 6.0.0 ~ 6.5.0");
        $roles = AdmOperationModule::roles();
        $form->multipleSelect('op_roles', '操作角色')->options($roles);
        $form->multipleSelect('super_role', '管理员')->options($roles);
    }

    public function getFormInfo($id): array
    {
        return BizPositionManagementModel::info($id);
    }

    /**
     * @throws Exception
     */
    public function save($input)
    {
        $en_name = self::multiFormInputFilter($input['en_name'] ?? []);
        $drop_version = self::multiFormInputFilter($input['drop_version'] ?? []);
        $tab = self::multiFormInputFilter($input['tab'] ?? []);
        $op_roles = self::multiFormInputFilter($input['op_roles'] ?? []);
        $super_role = self::multiFormInputFilter($input['super_role'] ?? []);
        $id = $input['id'] ?? 0;
        $rel = $input['rel'] ?? '';
        $style_type = $input['style_type'] ?? '';
        $title = $input['title'] ?? '';
        $sign = $input['sign'] ?? '';
        $v = $input['v'] ?? '';
        $options = $input['options'] ?? [];

        if (empty($en_name)) {
            throw new \Exception("资源位标识必须");
        }
        foreach ($en_name as $name) {
            if (!preg_match('/^[a-zA-Z]+\w+$/', $name)) {
                throw new \Exception("资源位标识必须字母开头,仅支持字母、数字、_组合");
            }
        }
        $rel = $rel == 'on' ? AdConfManagement::REL_OPEN : AdConfManagement::REL_CLOSE;
        $drop_version = array_sum($drop_version);
        $op_roles = empty($op_roles) ? '' : implode(',', $op_roles);
        $super_role = implode(',', $super_role);
        $alias = array_slice($en_name, 1);
        $en_name = current($en_name);
        $data = compact('en_name','alias','rel','style_type','title','sign','super_role','op_roles','v','tab','drop_version');
        if ($options) {
            if (isset($options['banner_link'])) $options['banner_link'] = self::multiFormInputFilter($options['banner_link']);
            if (isset($options['card_link'])) $options['card_link'] = self::multiFormInputFilter($options['card_link']);
            $data['options'] = $options;
        }
        $this->adminAuthorError();
        AdPositionManagement::createAppendPosition($id, $data);

    }

    public function adminAuthorError($id = 0)
    {
        if (!HhzEnv::isShopTest()) throw new Exception("仅限环境操作");
    }

    /**
     * @throws Exception
     */
    public function delete($id): int
    {
        $this->adminAuthorError();
        AdPositionManagement::delPosition($id);
        return 0;
    }


    /**
     * @throws Exception
     */
    public function put($input, $id)
    {
        $this->adminAuthorError();
        $name = $input['name'] ?? '';
        $value = $input['value'] ?? '';
        if (isset($input['rel'])) {
            $name = 'rel';
            $value = $input['rel'];
        }
        if (isset($input['app_tab'])) {
            $name = 'app_tab';
            $value = current($input['app_tab']);
        }
        if (isset($input['style_type'])) {
            $name = 'style_type';
            $value = current($input['style_type']);
        }
        if (isset($input['drop_version'])) {
            $name = 'drop_version';
            $value = array_sum($input['drop_version']);
        }
        if (isset($input['op_roles'])) {
            $name = 'op_roles';
            $value = empty($input['op_roles']) ? '' : implode(',', $input['op_roles']);
        }

        if (isset($input['super_role'])) {
            $name = 'super_role';
            $value = empty($input['super_role']) ? '' : implode(',', $input['super_role']);
        }

        $id = $input['pk'] ?? $id;
        $data = [];
        $conf = AdAdmin::positionList();
        if (!isset($conf[$id])) throw new \Exception('配置缺失');
        switch ($name) {
            case 'v':
                $data['v'] = $value;
                break;
            case 'sign':
                $data['sign'] = $value;
                break;
            case 'rel':
                $data['rel'] = $value;
                break;
            case 'alias':
                $data['alias'] = $value;
                break;
            case 'en_name':
                $data['en_name'] = $value;
                foreach ($conf as $v) {
                    if ($v['en_name'] == $value) throw new \Exception(vsprintf("%s与id[%s]标识一致", [$value,$v['id']]));
                }
                break;
            case 'title':
                $data['title'] = $value;
                if (mb_strlen($value) <= 0 || mb_strlen($value) > 40) {
                    throw new \Exception('资源位置名称长度1~40' . mb_strlen($value));
                }
                break;
            case 'app_tab':
                $data['tab'] = $value;
                $data['app_tab'] = ($value - 1) < 0 ? 0 : 1 << ($value - 1);
                break;
            case 'style_type':
                $data['style_type'] = $value;
                break;
            case 'drop_version':
                $data['drop_version'] = $value;
                break;
            case 'super_role':
                $data['super_role'] = $value;
                break;
            case 'op_roles':
                $data['op_roles'] = $value;
                break;
            default:
                throw new \Exception('未定义的快速更新字段');
        }

        if ($id && $data) {
            $conf[$id] = $data + $conf[$id];
            $new = [];
            foreach ($conf as $k => $v) {
                ksort($v);
                $new[$k] = $v;
            }
            AdPositionManagement::writeConf($new);
        }
    }

    /**
     * @throws Exception
     */
    public function sort($input)
    {
        $this->adminAuthorError();
        if (empty($input)) return;
        AdPositionManagement::sort($input);
    }


}